package com.dongzili.common.config.aspect;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongzili.common.vo.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class AsyncLogService {

    public static void logRequest(LogPrintInfo printInfo) {

        String traceId = printInfo.getTraceId();
        Object[] args = printInfo.getArgs();
        Object result = printInfo.getResult();
        long duration = printInfo.getDuration();
        RequestInfo request = printInfo.getRequest();
        String errMsg = printInfo.getErrMsg();
        try {
            // 记录请求信息
            log.info("{} - 请求开始：ip:{}, url: {}, method: {}, uri: {}, params: {}", traceId, request.getIp(), request.getUrl(), request.getMethod(), request.getUri(), request.getQueryString());
            log.info("{} - 请求内容：{}", traceId, JSONUtil.toJsonStr(args));
            
            if (errMsg != null) {
                // 记录异常信息
                log.info("{} - 请求执行异常：url:{}, 耗时：{} ms, 异常信息: {}", traceId, request.getUrl(), duration, errMsg);
            } else if (result != null) {
                // 记录返回信息
                int listSize = 0;
                try {
                    List<Object> data = new ArrayList<>();
                    String jsonString = "";
                    
                    if (result instanceof R<?>) {
                        R<?> apiResponse = (R<?>) result;
                        
                        if (apiResponse.getData() instanceof List<?>) {
                            listSize = ((List<?>) apiResponse.getData()).size();
                            if (listSize > 0) {
                                data.add(((List<?>) apiResponse.getData()).get(0));
                                data.add("剩余(共" + listSize + "条数据)......");
                            }
                        } else if (apiResponse.getData() instanceof Page<?>) {
                            Page<?> page = (Page<?>) apiResponse.getData();
                            listSize = page.getRecords().size();
                            if (listSize > 0) {
                                data.add(page.getRecords().get(0));
                                data.add("剩余(共" + listSize + "条数据)......");
                            }
                        }
                        
                        ObjectMapper objectMapper = new ObjectMapper();
                        objectMapper.registerModule(new JavaTimeModule());
                        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
                        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
                        jsonString = objectMapper.writeValueAsString(result);
                    }

                    // 打印返回参数
                    if (listSize > 0) {
                        log.info("{} - 请求返回3：url:{}, 耗时：{} ms, 返回数据: {}", traceId, request.getUrl(), duration, data);
                    } else {
                        log.info("{} - 请求返回2：url:{}, 耗时：{} ms, 返回数据: {}", traceId, request.getUrl(), duration, jsonString);
                    }
                } catch (Exception e) {
                    if (e instanceof com.fasterxml.jackson.databind.exc.InvalidDefinitionException) {
                        log.error("{} - 打印返回参数异常...{}", traceId, e.getMessage(), e);
                    } else {
                        log.error("{} - 打印返回参数异常...{}", traceId, e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("{} - 记录日志过程中发生异常: {}", traceId, e.getMessage(), e);
        }
    }



}